package cn.stylefeng.guns.modular.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.stylefeng.guns.modular.business.comment.YunHeKey;
import cn.stylefeng.guns.modular.business.entity.RiverDevelopment;
import cn.stylefeng.guns.modular.business.enums.RiverDevelopmentExceptionEnum;
import cn.stylefeng.guns.modular.business.mapper.RiverDevelopmentMapper;
import cn.stylefeng.guns.modular.business.pojo.RiverDevelopmentRequest;
import cn.stylefeng.guns.modular.business.service.RiverDevelopmentService;
import cn.stylefeng.guns.modular.business.service.SubUseBrowseService;
import cn.stylefeng.roses.kernel.auth.api.LoginUserApi;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 河道历史沿革业务实现层
 *
 * @author zhangyaowen
 * @date 2021/10/08 16:51
 */
@Service
public class RiverDevelopmentServiceImpl extends ServiceImpl<RiverDevelopmentMapper, RiverDevelopment> implements RiverDevelopmentService {

    @Resource
    private LoginUserApi loginUserApi;
    @Resource
    private SubUseBrowseService subUseBrowseService;

	@Override
    public void add(RiverDevelopmentRequest riverDevelopmentRequest) {
        RiverDevelopment riverDevelopment = new RiverDevelopment();
        BeanUtil.copyProperties(riverDevelopmentRequest, riverDevelopment);
        this.save(riverDevelopment);
    }

    @Override
    public void del(RiverDevelopmentRequest riverDevelopmentRequest) {
        RiverDevelopment riverDevelopment = this.queryRiverDevelopment(riverDevelopmentRequest);
        this.removeById(riverDevelopment.getId());
    }

    @Override
    public void edit(RiverDevelopmentRequest riverDevelopmentRequest) {
        RiverDevelopment riverDevelopment = this.queryRiverDevelopment(riverDevelopmentRequest);
        BeanUtil.copyProperties(riverDevelopmentRequest, riverDevelopment);
        this.updateById(riverDevelopment);
    }

    @Override
    public RiverDevelopment detail(RiverDevelopmentRequest riverDevelopmentRequest) {
        return this.queryRiverDevelopment(riverDevelopmentRequest);
    }

    @Override
    public PageResult<Map<String,Object>> findPage(RiverDevelopmentRequest riverDevelopmentRequest) {
        LambdaQueryWrapper<RiverDevelopment> queryWrapper = new LambdaQueryWrapper<>();
        String rhdRiver = riverDevelopmentRequest.getRhdRiver();
        queryWrapper.eq(ObjectUtil.isNotEmpty(rhdRiver), RiverDevelopment::getRhdRiver, rhdRiver);

        Page<RiverDevelopment> sysRolePage = this.page(PageFactory.defaultPage(), queryWrapper);

        PageResult<RiverDevelopment> riverDevelopmentPageResult = PageResultFactory.createPageResult(sysRolePage);
        PageResult<Map<String,Object>> pageResult = new PageResult<>();
        List<RiverDevelopment> riverDevelopmentList = riverDevelopmentPageResult.getRows();
        List<Map<String,Object>> mapList=new ArrayList<>();
        for(RiverDevelopment riverDevelopment:riverDevelopmentList){
            Map<String, Object> map = new HashMap<String, Object>();
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

            String jmid = YunHeKey.HDLSYG+riverDevelopment.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
//            String hdeve = StrUtil.sub(riverDevelopment.getHistoricalDevelopment(),0,20);
            map.put("title",riverDevelopment.getRhdTitle());
            map.put("rhdAnnalsfrom",riverDevelopment.getRhdAnnalsfrom());
            mapList.add(map);

        }
        pageResult.setRows(mapList);
        pageResult.setPageSize(riverDevelopmentPageResult.getPageSize());
        pageResult.setPageNo(riverDevelopmentPageResult.getPageNo());
        pageResult.setTotalPage(riverDevelopmentPageResult.getTotalPage());
        pageResult.setTotalRows(riverDevelopmentPageResult.getTotalRows());
        return pageResult;
    }

    @Override
    public List<Map<String, Object>> toReview(String jmid) {
        byte[] key =YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        String decryptStr = aes.decryptStr(jmid, CharsetUtil.CHARSET_UTF_8);
        //获取ID字符串YHSJ后面真实的的id
        String id = StrUtil.subAfter(decryptStr,YunHeKey.HDLSYG,false);
        HttpServletRequest request = HttpServletUtil.getRequest();
        Long userid;
        if (ObjectUtil.isNotNull(request)) {

            LoginUser loginUser = loginUserApi.getLoginUser();
            userid = loginUser.getUserId();
        } else {
            throw new ServiceException(RiverDevelopmentExceptionEnum.REQUEST_EMPTY);
        }
        LambdaQueryWrapper<RiverDevelopment> queryWrapper = new LambdaQueryWrapper<>();
        if ("".equals(id)) {
            List<Map<String, Object>> mapLists = new ArrayList<>();
//            Map<String, Object> map =new HashMap<>();
//            map.put("error","id为空");
            return mapLists;
        }
        queryWrapper.eq(ObjectUtil.isNotEmpty(id), RiverDevelopment::getId, id);
        List<RiverDevelopment> riverDevelopmentList = this.list(queryWrapper);
        if(userid != 0l && userid != -1l) {
            subUseBrowseService.saveBrowse(YunHeKey.HEDAO,riverDevelopmentList.get(0).getRhdTitle(),userid,request);
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (RiverDevelopment riverDevelopment : riverDevelopmentList) {

            Map<String, Object> map = new HashMap<String, Object>();
            map = JSONObject.parseObject(JSONObject.toJSONString(riverDevelopment), Map.class);

            // 获取类的属性
            Field[] declaredFields = RiverDevelopment.class.getDeclaredFields();
            List<Map<String, Object>> mplist = new ArrayList<>();
            // 遍历属性，获取属性上ApiModelProperty的值，属性的名，存入Properties
            if (declaredFields.length != 0) {

                int i = 1;
                Map<String, Object> p = new HashMap<String, Object>();

                for (Field field : declaredFields) {

                    Map<String, Object> mp = new HashMap<String, Object>();
                    if (field.getAnnotation(ApiModelProperty.class) != null) {
                        //获取注解属性
                        ApiModelProperty aa = field.getAnnotation(ApiModelProperty.class);
                        // key和value可根据需求存
                        // 这存的key为注解的值，value为类属性名
                        if ("rhdTitle".equals(field.getName()) || "historicalDevelopment".equals(field.getName()) ) { //组成标题
                            if ("historicalDevelopment".equals(field.getName())) {
                                p.put(field.getName(), map.get(field.getName()));
                            }else {
                                p.put("title", map.get(field.getName()));
                            }
                        }else {
                            mp.put("key", aa.value());
                            mp.put("value", map.get(field.getName()));

                            if (i != 1) {
                                mplist.add(mp);
                            }
                        }
                    }
                    i++;
                }
                p.put("list", mplist);
                if (i != 1) {
                    mapList.add(p);
                }
            }
        }
        return mapList;
    }

    @Override
    public List<RiverDevelopment> findList(RiverDevelopmentRequest riverDevelopmentRequest) {
        LambdaQueryWrapper<RiverDevelopment> wrapper = this.createWrapper(riverDevelopmentRequest);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author zhangyaowen
     * @date 2021/10/08 16:51
     */
    private RiverDevelopment queryRiverDevelopment(RiverDevelopmentRequest riverDevelopmentRequest) {
        RiverDevelopment riverDevelopment = this.getById(riverDevelopmentRequest.getId());
        if (ObjectUtil.isEmpty(riverDevelopment)) {
            throw new ServiceException(RiverDevelopmentExceptionEnum.RIVERDEVELOPMENT_NOT_EXISTED);
        }
        return riverDevelopment;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/10/08 16:51
     */
    private LambdaQueryWrapper<RiverDevelopment> createWrapper(RiverDevelopmentRequest riverDevelopmentRequest) {
        LambdaQueryWrapper<RiverDevelopment> queryWrapper = new LambdaQueryWrapper<>();

        Long id = riverDevelopmentRequest.getId();
        String rhdRiver = riverDevelopmentRequest.getRhdRiver();
        String historyDating = riverDevelopmentRequest.getHistoryDating();
        String theCommon = riverDevelopmentRequest.getTheCommon();
        String historicalDevelopment = riverDevelopmentRequest.getHistoricalDevelopment();
        String rhdAnnalsfrom = riverDevelopmentRequest.getRhdAnnalsfrom();
        String rhdAnnalspage = riverDevelopmentRequest.getRhdAnnalspage();

        queryWrapper.eq(ObjectUtil.isNotNull(id), RiverDevelopment::getId, id);
        queryWrapper.like(ObjectUtil.isNotEmpty(rhdRiver), RiverDevelopment::getRhdRiver, rhdRiver);
        queryWrapper.like(ObjectUtil.isNotEmpty(historyDating), RiverDevelopment::getHistoryDating, historyDating);
        queryWrapper.like(ObjectUtil.isNotEmpty(theCommon), RiverDevelopment::getTheCommon, theCommon);
        queryWrapper.like(ObjectUtil.isNotEmpty(historicalDevelopment), RiverDevelopment::getHistoricalDevelopment, historicalDevelopment);
        queryWrapper.like(ObjectUtil.isNotEmpty(rhdAnnalsfrom), RiverDevelopment::getRhdAnnalsfrom, rhdAnnalsfrom);
        queryWrapper.like(ObjectUtil.isNotEmpty(rhdAnnalspage), RiverDevelopment::getRhdAnnalspage, rhdAnnalspage);

        return queryWrapper;
    }

}